// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.ComponentModel.DataAnnotations.Schema;
using SnapObjects.Commons;

namespace SnapObjects.Data
{
    /// <summary>
    ///     Sets the joined table to be used in a model class. Multiple JoinTable attributes can be applied to one model class.
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = true, Inherited = true)]
    public class JoinTableAttribute : TableAttribute, IJoinTable
    {
        /// <summary>
        ///     Initializes a new instance of the JoinTableAttribute class.
        /// </summary>
        /// <param name="name">The name of the table to join.</param>
        public JoinTableAttribute(string name)
            : base(name)
        {
            Check.NotEmpty(name, nameof(name));

            this.JoinType = SqlJoinType.Join;
        }

        /// <summary>
        ///     Initializes a new instance of the JoinTableAttribute class.
        /// </summary>
        /// <param name="alias">The alias of the table to join.</param>
        /// <param name="name">The name of the table to join.</param>
        public JoinTableAttribute(string alias, string name)
            : base(name)
        {
            Check.NotEmpty(alias, nameof(alias));
            Check.NotEmpty(name, nameof(name));

            this.AliasDefined = true;
            this.Alias = alias.Trim();
            this.JoinType = SqlJoinType.Join;
        }

        int IJoinTable.Id => this.Id;

        internal int Id { get; set; }

        /// <summary>
        ///     Gets the alias of the table to join.
        /// </summary>
        public string Alias { get; }

        /// <summary>
        ///     Gets or sets the raw SQL search condition on which the join is based.
        /// </summary>
        public string OnRaw { get; set; }

        /// <summary>
        ///     Gets or sets the type of join operator.
        /// </summary>
        public SqlJoinType JoinType { get; set; }

        /// <summary>
        ///     Gets whether the table to join has an alias or not.
        /// </summary>
        public bool AliasDefined { get; }
    }
}
